<template>
	<view class="content">
	
		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view 
				v-for="(item,index) in tabBars" :key="item.id"
				class="nav-item"
				:class="{textLinear: index === tabCurrentIndex}"
				:id="'tab'+index"
				@click="changeTab(index,item.state)"
			>{{item.name}}</view>
		</scroll-view>
		
		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh" @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper 
				id="swiper"
				class="swiper-box" 
				:duration="300" 
				:current="tabCurrentIndex"
				:disable-touch="true"
			>
				<swiper-item v-for="tabItem in tabBars" :key="tabItem.id">
					<scroll-view 
						class="panel-scroll-box" 
						:scroll-y="enableScroll" 
						@scrolltolower="loadMore"
						>
						
						<view class="order-list-box" v-if="tabItem.newsList.length>0">
							<view class="order-list" v-for="(item,index) in tabItem.newsList" :key="index">
								<view v-if="item.shop_price==null" class="product_down"></view>
								
								<view class="order-top">
									<view class="order-create-time">
										{{item.create_time}} {{item.seller}}<text class="ml-10" v-if="item.is_baojia_zone ==1">(保价区)</text>
									</view>
									<view class='order-status' v-if="item.pay_status == 0">
										<view class='order-apply' v-if="item.order_state == 8">(已申请售后)</view>
										<view class='order-apply' v-else-if="item.order_state == 7">（已取消）</view>
										<view v-else>未支付</view>
									</view>
									<view class='order-status' v-else-if="item.pay_status == 1">
										{{item.order_state_text}}
									</view>
								</view>
								
								<navigator open-type="navigate" hover-class="none" class="good" :url="'/pages/jewel/order/orderdetail?order_id='+item.id">
									<view class="lease-img">
										<image :src="item.goods_img" mode="aspectFit"></image>
									</view>
									<view class="lease-info">
										<view class="lease-title">{{item.goods_name}}</view>
										<view class="lease-attr font-color-hs">{{item.item_names}}</view>
									</view>
									<view class="lease-price">
										<view class="lease-now">¥{{item.shop_price}}</view>
										<view class="lease-num font-color-hs">x{{item.buy_num}}</view>
									</view>
								</navigator>
								
								<view class="total-cont">共{{item.buy_num}}件商品，已支付：¥{{item. pay_amount }}</view>
								<view class="order-handle-box" v-if="item.shop_price!=null">
									<view class="order-handle" @tap="get_benefit(item.order_no)" v-if="item.pool_benefit_text != 0">{{item.pool_benefit_text.title}}</view>
									<view class="order-handle" @tap="handle_order(item.id, 1,'cancel_order')" v-if="item.pay_status == 0 && item.order_state != 7">取消订单</view>
									<view class="order-handle" @tap="go_keep_detail(item.order_no)" v-if="item.order_state == 9">查看寄存</view>
									<view class='order-handle' @tap='consign_select(item.order_no)' v-if="item.consign_end_info.consign_end == 1">{{item.consign_end_info.text}}</view>
									<view class='order-handle' @tap='consign_order(item.id, item.order_no)' v-if="item.is_consign && item.seller_id == 0">申请寄存</view>
									<view class='order-handle' @tap='cancel_consignation(item.id, 1)' v-if="item.pay_status == 1 && item.order_state == 9 && item.consign_end_info.consign_end !='1'">取消寄存</view>
									<view class="order-handle" @tap="handle_order(item.id, 2, 'finish_order')" v-if="item.pay_status == 1 && item.order_state == 3">确认收货</view>
									<view class="order-handle" v-if="item.is_refund && item.seller_id == 0" @tap="apply(item.id)">{{item.order_refund_text}}</view>
									<view class="order-handle" @tap="baojia(item.order_no,item.baojia_tip)" v-if="item.order_state == 5 && item.has_baojia == 0 && item.is_baojia_zone == 1">申请保价</view>
									<view class="order-handle" v-if="item.pay_status == 1 && item.seller_id > 0" @tap="apply(item.id)">申请退换</view>
									<navigator hover-class="none" open-type="navigate"
										:url="'/pages/jewel/order/orderinfo?order_no='+item.order_no" 
										v-if="item.pay_status == 0 && item.order_state != 7"
									><view class='order-handle dopay'>立即付款</view>
									</navigator>
								</view>
							</view>
						</view>
						
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus" v-if="tabBars[tabCurrentIndex].newsList.length == 0 || tabBars[tabCurrentIndex].newsList.length > 10"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>
		
		<uni-transition :mode-class="['fade']" :styles="maskClass" :show="isShowRed"/>
		<uni-transition :duration="500" :mode-class="modeClass" :styles="transfromClass" :show="isShowRed">
			<view class="lottery-redpack">
				<image class="lottery-redpack-bg" src="../../../static/images/lottery_draw/redpack_bg3.png" mode="widthFix"></image>
				<view class="lottery-redpack-tips">
					<view class="lottery-redpack-tips-text">获得</view>
					<view class="lottery-redpack-tips-entext">恒朗报销金</view>
					<view class="lottery-redpack-tips-money">￥{{redPackMoney}}</view>
				</view>
				<view class="lottery-redpack-close"><image src="../../../static/icons/jewel/sign_close.png" @tap="showToggle('closeRed')"></image></view>
			</view>
		</uni-transition>
	</view>
</template>

<script>
	const tabData = [{
		name: '全部',
		id: '1',
		state: 1
	}, {
		name: '待付款',
		id: '2',
		state: 6
	}, {
		name: '待收货',
		id: '3',
		state: 3
	}, {
		name: '已完成',
		id: '4',
		state: 4
	}, {
		name: '已取消',
		id: '5',
		state: 7
	}, {
		name: '已寄存',
		id: '6',
		state: 9
	},];
	import jewel from '@/common/common_zb.js';
	let windowWidth = 0, scrollTimer = false, tabBar, that;
	export default {
		data() {
			return {
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				page:1,
				totalPages:1,
				Consignation: [], // 寄存的时间
				modeClass:['fade'],
				transfromClass: {
					'position': 'fixed',
					'bottom': 0,
					'top': 0,
					'left': 0,
					'right': 0,
					/* #ifndef APP-NVUE */
					'display': 'flex',
					/* #endif */
					'justify-content': 'center',
					'align-items': 'center',
					'z-index':11
				},
				maskClass: {
					'position': 'fixed',
					'z-index':9,
					'bottom': 0,
					'top': 0,
					'left': 0,
					'right': 0,
					'background-color': 'rgba(0, 0, 0, 0.4)'
				},
				isShowRed:false,
				redPackMoney:0
			}
		},
		mounted() {
			that = this
		},
		onLoad({tarBarType}) {
			let that = this
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			that.tabCurrentIndex = Number(tarBarType?tarBarType:0)
			this.loadTabbars();
			jewel.post('order/getConsign', {}, false, function(res) {
				that.Consignation = res.data.data;
			})
		},
		methods: {
			//获取分类
			loadTabbars(){
				let tabList = tabData;
				tabList.forEach(item=>{
					item.newsList = [];
					item.loadMoreStatus = 1;  //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0;
				})
				this.tabBars = tabList;
				this.loadNormal();
			},
			//tab切换
			async changeTab(e,state){
				if(e == this.tabCurrentIndex) return false
				if(scrollTimer){
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				
				//e=number为点击切换，e=object为swiper滑动切换
				// if(typeof e === 'object'){
				// 	index = e.detail.current
				// }
				if(typeof tabBar !== 'object'){
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0; 
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if(i === index){
						nowWidth = result.width;
					}
				}
				if(typeof e === 'number'){
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index; 
					this.tabBars[index].loadMoreStatus = 1
				}
				
				this.tabBars[this.tabCurrentIndex].newsList = []
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(()=>{
					if (width - nowWidth/2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth/2 - windowWidth / 2;
					}else{
						this.scrollLeft = 0;
					}
					this.tabCurrentIndex = index; 
					this.totalPages = 1
					this.loadNormal()
				}, 300)
				
			},
			// 获取订单列表
			loadNewsList(type){
				let that = this
				let tabItem = that.tabBars[that.tabCurrentIndex];
				if(type === 'add'){
					tabItem.loadMoreStatus = 1
				}
				// #ifdef APP-PLUS
				if(type === 'refresh'){
					tabItem.refreshing = true;
				}
				// #endif
				if(that.page <= that.totalPages){
					jewel.post('order/get_order_list',{type:tabItem.state,page:that.page,franchise_order:1},true,function(res){
						if(res.data.code == 0){
							switch(type){
								case 'normal':
									tabItem.newsList = res.data.data
									tabItem.loadMoreStatus = res.data.count == 0? 4: 0;
									that.totalPages = res.data.total_pages
								break;
								case 'refresh':
									//下拉刷新 关闭刷新动画
									that.$refs.mixPulldownRefresh && that.$refs.mixPulldownRefresh.endPulldownRefresh();
									// #ifdef APP-PLUS
									tabItem.refreshing = false;
									// #endif
									
									tabItem.newsList = res.data.data
									that.totalPages = res.data.total_pages
									if(tabItem.newsList.length === 0) tabItem.loadMoreStatus = 2
								break;
								case 'add':
									tabItem.newsList = tabItem.newsList.concat(res.data.data)
									tabItem.loadMoreStatus = 0;
								break;
							}
						}
					})
				}else{
					tabItem.loadMoreStatus = 2
				}
			},
			// 取消寄存
			cancel_consignation(order_id, type) {
				let that = this;
				if (type == 1) {
					uni.showModal({
						title: '提示',
						content: '确认要取消寄存该订单吗',
						success: function(res) {
							if (res.confirm) {
								jewel.post('order/cancel_consignation', {
									order_id: order_id
								}, true, function(res) {
									let resdata = res.data;
									if (resdata.code == '0') {
										jewel.showToast(resdata.msg);
										that.loadNormal();
									} else if (resdata.code == 2) {
										uni.showModal({
											title: '提示',
											content: resdata.msg,
											success: function(res) {
												if (res.confirm) {
													that.cancel_consignation(order_id, 2);
												}
											}
										})
									} else {
										jewel.showToast(resdata.msg);
									}
								})
							}
						}
					})
				} else {
					jewel.post('order/cancel_consignation', {
						order_id: order_id,
						toast: 1
					}, true, function(res) {
						let resdata = res.data;
						jewel.showToast(resdata.msg);
						if (resdata.code == '0') {
							that.loadNormal();
						}
					})
				}
			
			},
			// 申请寄存
			consign_order(order_id, order_no){
				let that = this;
				uni.showActionSheet({
				    itemList: that.Consignation,
				    success: function (res) {
						let tapIndex = res.tapIndex;
						let consign_type = that.Consignation[tapIndex];
						uni.showModal({
							title: '提示',
							content: '确认要寄存该订单吗',
							success: function (res) {
								if (res.confirm) {
									jewel.post('order/consign_order', {order_id: order_id, consign_type: consign_type}, true, function (res){
										let resdata = res.data;
										jewel.showToast(resdata.msg);
										if(resdata.code == '0') {
											that.loadNormal();
											setTimeout(function (){
												console.log(order_no)
												uni.navigateTo({
													url: '/pages/jewel/agent_jewel/keep_detail?order_no=' + order_no
												})
											}, 1000);
										}
									})
								}
							}
						})
				    }
				});
			},
			consign_select(order_no){
				let that = this;
				uni.showActionSheet({
				    itemList: ['续期'],
				    success: function (res) {
						that.bIsShowLoading = true;
						jewel.post('order/consign_renewal', {order_no: order_no, action: res.tapIndex}, true, function (res){
							that.bIsShowLoading = false;
						})
					//	that.loadNormal();
				    },
				    fail: function (res) {
				        console.log(res.errMsg);
				    }
				});
			},
			// 申请享退
			apply(order_id){
				uni.navigateTo({
					url: '/pages/jewel/order/order_apply?order_id=' + order_id
				})
			},
			// 查看寄存
			go_keep_detail(order_no) {
				uni.navigateTo({
					url: '/pages/jewel/agent_jewel/keep_detail?order_no=' + order_no
				})
			},
			// 取消订单，确认收货
			handle_order(order_id, type, url){
				let that = this;
				let text = type == 1 ? '确认要取消订单吗？': '确认已收到货了吗？';
				let sendurl = 'order/' + url;
				uni.showModal({
					title: '提示',
					content: text,
					success: function (res) {
						if (res.confirm) {
							uni.showLoading()
							jewel.post(sendurl, {order_id: order_id}, true, function (res){
								let resdata = res.data;
								setTimeout(function (){
									uni.hideLoading()
									jewel.showToast(resdata.msg)
									that.loadNormal();
								}, 1000);
							})
						}
					}
				})
			},
			baojia(order_no,baojia_tip){
				let that = this
				uni.showModal({
					title: '提示',
					content: baojia_tip,
					success: function (res) {
						if (res.confirm) {
							jewel.post('Order/baojiaBack',{order_no:order_no},true,function(res){
								jewel.showToast(res.data.msg);
								setTimeout(function (){
									that.loadNormal();
								}, 1000);
							})
						}
					}
				})
			},
			//下拉刷新
			onPulldownReresh(){
				this.page = 1
				this.totalPages = 1
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore(){
				this.page++;
				this.loadNewsList('add');
			},
			loadNormal(){
				this.page = 1;
				this.loadNewsList('normal');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable){
				if(this.enableScroll !== enable){
					this.enableScroll = enable;
				}
			},

			//获得元素的size
			getElSize(id) { 
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			showToggle(type){
				switch(type){
					case 'showRed':
						this.isShowRed = true
					break;
					case 'closeRed':
						this.isShowRed = false
					break;
				}
			},
			get_benefit(order_no){
				let that = this
				uni.showLoading({
					title:'领取中...',
					mask:true
				})
				jewel.post('order/get_pool_benefit',{order_no:order_no},true,function(res){
					setTimeout(()=>{
						uni.hideLoading()
						if(res.data.code == 1){
							that.showToggle('showRed')
							that.redPackMoney = res.data.pool_benefit
							that.loadNormal()
						}else{
							jewel.showToast(res.data.msg)
						}
					},1000)
				})
			}
		}
	}
</script>

<style lang="scss">
	
	page, .content{
		background-color: #efefef;
		height: 100%;
		overflow: hidden;
	}

	/* 顶部tabbar */
	.nav-bar{
		position: relative;
		z-index: 10;
		height: 76rpx;
		white-space: nowrap;
		background-color: #fff;
		box-shadow: 0 2upx 8upx rgba(0,0,0,.06);
		display: flex;
		.nav-item{
			display: inline-block;
			width: 125rpx;
			height: 76rpx;
			text-align: center;
			line-height: 76rpx;
			font-size: 28rpx;
			color: #333333;
			position: relative;
			flex: 1;
			&:after{
				content: '';
				width: 0;
				height: 4rpx;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}
		.textLinear{
			&:after{
				width: 50%;
				background: linear-gradient(to bottom right, #b676af, #ea669f, #f7c07e);
			}
		}
	}

	.swiper-box{
		height: 100%;
	}

	.panel-scroll-box{
		height: 100%;
		.panel-item{
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}
	
	.order-list-box {
		width: 100%;
		overflow: hidden;
		margin-top: 75rpx;
		.order-list {
			width: 720rpx;
			background: #fff;
			margin: 0 auto;
			position: relative;
			margin-bottom: 20rpx;
			box-sizing: border-box;
			padding: 15rpx;
			padding-top: 0;
			border-radius: 5px;
			.product_down{
				background-image: url('~@/static/images/jewel/product_down.png');
				background-size: 100%;
				background-repeat: no-repeat;
				width: 135rpx;
				height: 135rpx;
				position: absolute;
				right: 0rpx;
				top: 0rpx;
			}
			.order-top{
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 90rpx;
				border-bottom: 1px solid #dfdfdf;
				.order-create-time{
					color: #333333;
					font-size: 26rpx;
				}
				.order-status{
					color: #333333;
					font-size: 28rpx;
				}
			}
		}
		&:first-child{
			margin-top: 20rpx;
		}
		
	}
	

	.good {
		overflow: hidden;
		border-bottom: 1px solid #ddd;
		display: flex;
		align-items: flex-start;
		padding: 20rpx 0;
	}
	
	.lease-img {
		width: 144rpx;
		height: 144rpx;
		margin-right: 21rpx;
	}
	
	.lease-img image {
		width: 100%;
		height: 100%
	}
	
	.lease-info {
		width: 370rpx;
		font-size: 26rpx;
		overflow: hidden;
	}
	
	.lease-title {
		max-height: 68rpx;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		font-size: 28rpx;
		line-height: 34rpx;
	}
	
	.lease-attr {
		max-height: 68rpx;
		overflow: hidden;
		font-size: 26rpx;
		margin-top: 10rpx;
		line-height: 34rpx;
	}
	
	.lease-price {
		text-align: right;
		font-size: 26rpx;
		width: 160rpx;
	}
	
	.lease-market-price {
		text-decoration: line-through;
	}
	
	.lease-now {
		color: #343434;
		font-size: 28rpx;
	}
	
	.font-color-hs {
		color: #808080;
	}
	
	.order-handle-box {
		display: flex;
		justify-content: flex-end;
		font-size: 26rpx;
	}
	
	.order-handle {
		height: 45rpx;
		padding: 0 20rpx;
		border: 1px solid #666666;
		text-align: center;
		line-height: 45rpx;
		border-radius: 20px;
		color: #333333;
		margin-left: 20rpx;
	}
	.total-cont{
		font-size: 26rpx;
		color: #333333;
		text-align: right;
		padding: 24rpx 0;
	}
	.dopay {
		color: #fff;
		background: linear-gradient(to bottom right, #b676af, #ea669f, #f7c07e);
		border: none;
		line-height: 49rpx;
		height: 49rpx;
	}
	
	.order-apply {
		display: inline-block;
		color: green
	}
	.m-no-data image{
		width: 100%;
		height: 100%;
	}
	.ml-10{
		margin-left: 10rpx;
	}
	.lottery-redpack{
		width: 530rpx;
		height: 652rpx;
		position: relative;
		z-index: 10;
		&-bg{
			width: 530rpx;
			height: 652rpx;
			position: absolute;
			z-index: -1;
			top: 0;
			left: 0;
		}
		&-tips{
			width: 100%;
			text-align: center;
			&-text{
				font-size: 57rpx;
				color: #ebae38;
				margin-top: 50rpx;
			}
			&-entext{
				font-size: 57rpx;
				color: #ebae38;
				margin-top: 120rpx;
			}
			&-money{
				margin-top: 50rpx;
				font-size: 110rpx;
				color: #fbd41f;
				text-shadow:0px 4px 0px rgba($color: #5f5f5f, $alpha: 0.34);
			}
		}
		&-close{
			width: 86rpx;
			height: 86rpx;
			margin: 0 auto;
			margin-top: 30rpx;
			display: block;
			position: absolute;
			bottom: -150rpx;
			left: 50%;
			transform: translateX(-50%);
			image{
				width: 86rpx;
				height: 86rpx;
			}
		}
	}
	
	
</style>
